#!/bin/sh

#this script is brutal and verbose, has no tricks and is quite linear, then
#quite easy to deal with
#for the moment, it's hardcoded for a gcc toolchain... BAD! Since now
#gcc is a c++ piece of shit

# stolen from ffmpeg configure like a pig
set -e

# Prevent locale nonsense from breaking basic text processing.
LC_ALL=C
export LC_ALL

init_file_name=init

#-------------------------------------------------------------------------------
#default source files in the binary
init_ulinux_src_files='
ulinux/utils/mem.c
ulinux/utils/ascii/string/vsprintf.c
'
init_src_files=init.c
#-------------------------------------------------------------------------------

clean_do()
{
    all_init_src_files="$init_src_files $init_ulinux_src_files"

    rm -f $init_file_name
    for init_src_file in $all_init_src_files
    do
      init_pp_file=${init_src_file%.c}
      init_pp_file=${init_pp_file}.pp.c
      rm -f ${init_pp_file}
      init_o_file=${init_src_file%.c}
      init_o_file=${init_o_file}.o
      rm -f ${init_o_file}
      #clean directories, but keep root of build tree
      tgt_dir=$(dirname $init_src_file)
      if test -d $tgt_dir -a "$tgt_dir" != "."; then
        rmdir --ignore-fail-on-non-empty -p $tgt_dir
      fi
    done
    exit 0
}

sep_start()
{
  printf '###############################################################################\n'
}

sep_end()
{
  printf '###############################################################################\n\n'
}

subsep_start()
{
  printf '*******************************************************************************\n'
}

subsep_end()
{
  printf '*******************************************************************************\n'
}

################################################################################

is_in(){
    value=$1
    shift
    for var in $*; do
        [ $var = $value ] && return 0
    done
    return 1
}

die_unknown(){
    echo "Unknown option \"$1\"."
    echo "See $0 --help for available options."
    exit 1
}

set_default(){
    for opt; do
        eval : \${$opt:=\$${opt}_default}
    done
}

CMDLINE_SET='
    init_cpp
    init_cc
    init_ld
    init_ulinux_arch
'

################################################################################

#command line set defaults
#-------------------------------------------------------------------------------
#This defaults are for gcc, tested with version 4.7.3. You will need to
#override those for you compiler (tinycc/open64/pcc...). Additionnally, source
#support for different toolchains is not done.
#The right way to do it is to have a toolchain abstraction layer since there are
#no accurate enough standards
init_cpp_default='gcc -E -Wall -Wextra'
init_cc_default='gcc -nostdinc -Wall -Wextra -std=gnu99 -O0 -c'
init_ld_default='ld -nostdlib -O10 -s'
#-------------------------------------------------------------------------------
init_ulinux_arch_default=$(uname -m | sed -e s/i.86/i386/ -e s/parisc64/parisc/ -e s/sun4u/sparc64/ -e s/arm.*/arm/ -e s/sa110/arm/ -e s/sh.*/sh/)

set_default $CMDLINE_SET

################################################################################

show_help(){
    cat <<EOF
Usage: make [options] [operations]

Operations: [default is to build the the init process binary]:
  clean                                clean build products

Options: [defaults in brackets after descriptions]

Help options:
  --help                               print this message

Standard options:
  --quiet                              init will be silenced (output code compiled out)
  --no-tty                             init won't respawn login processes on ttys

Advanced options:
  --init-cpp=CPP                       use CPP compiler command line CPP for target init process [$init_cpp_default]
  --init-cc=CC                         use C compiler command line CC for target init process objects [$init_cc_default]
  --init-ld=LD                         use linker command line LD for target init process [$init_ld_default]
  --init-ulinux-arch=ARCH              use ulinux ARCH for target init process [$init_ulinux_arch]
EOF
  exit 0
}

################################################################################

for opt do
    optval="${opt#*=}"
    case "$opt" in
        clean) clean_do
        ;;
        --help|-h) show_help
        ;;
        --quiet)
            CPPFLAGS="$CPPFLAGS -DQUIET"
            init_ulinux_src_files="$init_ulinux_src_files/ulinux\/utils\/ascii\/string\/vsprintf.c/"
            init_ulinux_src_files="$init_ulinux_src_files/ulinux\/utils\/mem.c/"
        ;;
	--no-tty) CPPFLAGS="$CPPFLAGS -DNO_TTY"
	;;
        *)
            optname=${opt%%=*}
            optname=${optname#--}
            optname=$(echo "$optname" | sed 's/-/_/g')
            if is_in $optname $CMDLINE_SET; then
                eval $optname='$optval'
            else
                die_unknown $opt
            fi
        ;;
    esac
done

################################################################################

sep_start;echo 'looking for source path:'
if test -f make; then
    src_path=.
else
    src_path=$(cd $(dirname "$0"); pwd)
    echo "$src_path" | grep -q '[[:blank:]]' &&
        die "out of tree builds are impossible with whitespace in source path."
    test -e "$src_path/config.h" &&
        die "out of tree builds are impossible with config.h in source dir."
fi
echo "source path is $src_path";sep_end

################################################################################

sep_start;echo 'configure ulinux src tree for target arch:'
rm -f $src_path/ulinux/arch
ln -s archs/$init_ulinux_arch $src_path/ulinux/arch
echo "init ulinux arch is $init_ulinux_arch"
sep_end

################################################################################

#from here we merge all source files
all_init_src_files="$init_src_files $init_ulinux_src_files"

################################################################################

sep_start;echo 'C preprocess init src files:'
for init_src_file in $all_init_src_files
do
    init_pp_c_file=${init_src_file%.c}
    init_pp_c_file=${init_pp_c_file}.pp.c
    echo "INIT_CPP $init_src_file->$init_pp_c_file"
    mkdir -p $(dirname $init_pp_c_file)
    $init_cpp $CPPFLAGS -I. -I$src_path -o $init_pp_c_file \
                                                        $src_path/$init_src_file
    init_pp_c_files="$init_pp_c_file $init_pp_c_files"
done
sep_end

################################################################################

sep_start;echo 'compile init preprocessed src files:'
for init_pp_c_file in $init_pp_c_files
do
    init_obj_file=${init_pp_c_file%.pp.c}
    init_obj_file=${init_obj_file}.o
    echo "INIT_CC $init_pp_c_file-->$init_obj_file"
    $init_cc $CFLAGS -o $init_obj_file $init_pp_c_file
    init_obj_files="$init_obj_file $init_obj_files"
done
sep_end

################################################################################

sep_start;echo 'link the init objects to produce the init binary:'
echo "INIT_LD $init_file_name"
echo $init_ld -o $init_file_name $init_obj_files
$init_ld -o $init_file_name $init_obj_files
sep_end
